package com.ruoyi.canteen.controller.v1;

import com.auth0.jwt.interfaces.Claim;
import com.ruoyi.canteen.domain.CanteenUser;
import com.ruoyi.canteen.service.ICanteenUserService;
import com.ruoyi.canteen.utils.BeanCopyUtils;
import com.ruoyi.canteen.utils.JwtToken;
import com.ruoyi.canteen.vo.UserWx;
import com.ruoyi.common.core.domain.AjaxResult;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * @Author Ryan
 * @Date 2021/9/19 20:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/v1/user")
public class UserApiController {

    @Autowired
    private ICanteenUserService canteenUserService;

    @PostMapping("/wx_info")
    public AjaxResult updateUserInfo(@RequestBody UserWx user) {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(user.getToken());
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenUser canteenUser = new CanteenUser();
            canteenUser.setId(uid);
            BeanCopyUtils.copyProperties(user, canteenUser);
            canteenUser.setUpdateTime(new Date());
            canteenUserService.updateUserWxInfo(canteenUser);
            return AjaxResult.success(canteenUser);
        }else{
            return AjaxResult.error("授权失败");
        }
    }


    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/getDetail/{token}")
    public AjaxResult getDetail(@PathVariable("token") String token)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenUser canteenUser =
                    canteenUserService.selectCanteenUserById(uid.toString());
            return AjaxResult.success(canteenUser);
        }else{
            return AjaxResult.error("token 过期");
        }
    }




}
